<?php

namespace AdminPanel\ContentBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AdminPanel\ContentBundle\Entity\Content;
use AdminPanel\ContentBundle\Form\ContentType;

/**
 * Content controller.
 *
 */
class ContentController extends Controller
{
    /**
     * Lists all Content entities.
     *
     */
    public function indexAction()
    {
        // Set controller names
        \AdminPanel\DashboardBundle\Utils\adminCustomClass::defineControllerName($this);       
      
        $entities = $this->getDoctrine()->getManager()->getRepository('AdminPanelContentBundle:Content')->findAll();
        
        return $this->render('AdminPanelContentBundle:Content:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Finds and displays a Content entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelContentBundle:Content')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Content entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        
        return $this->render('AdminPanelContentBundle:Content:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to create a new Content entity.
     *
     */
    public function newAction()
    {
        $entity = new Content();
        $form   = $this->createForm(new ContentType(), $entity);

        return $this->render('AdminPanelContentBundle:Content:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a new Content entity.
     *
     */
    public function createAction(Request $request)
    {
      
        $em = $this->getDoctrine()->getManager();
        
        $entity  = new Content();
        $form = $this->createForm(new ContentType(), $entity);
        $form->bind($request);

        
        // Check title
        $requestFormArray = $request->request->get('adminpanel_contentbundle_contenttype');
        $issetTitle = $em->getRepository('AdminPanelContentBundle:Content')->findOtherActiveContentByTitle($requestFormArray['content_title']);
        if ($issetTitle) {
          $this->get('session')->setFlash('error', 'Уучлаарай өмнө нь хадгалагдсан "' . $requestFormArray['content_title'] . '" гарчигтай идэвхитэй контент байна.');
          return $this->render('AdminPanelContentBundle:Content:edit.html.twig', array(
                      'entity' => $entity,
                      'edit_form' => $form->createView(),                      
                  ));
        }
        
        if ($form->isValid()) {
            
            $em->persist($entity);
            $em->flush();

            
            if (isset($requestFormArray['menu'])) {
            $menu = $em->getRepository('AdminPanelMenuBundle:Menu')->find($requestFormArray['menu']);
            if ($menu) {
              $menu->setSlug('/content/' . $entity->getContentTitle());
              $menu->setContentId($entity->getId());
              $em->persist($menu);
              $em->flush();
            }
          }
            
            $this->get('session')->setFlash('notice', $this->container->getParameter('successSave'));          
            return $this->redirect($this->generateUrl('content'));
        }

        return $this->render('AdminPanelContentBundle:Content:index.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Content entity.
     *
     */
    public function editAction($id)
    {
      
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelContentBundle:Content')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Content entity.');
        }

        $editForm = $this->createForm(new ContentType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        // Get menu list
        $menuArray = $em->getRepository('AdminPanelMenuBundle:Menu')->getAllParentMenuByStatus($this->container->getParameter('statusActive'));
        for ($i = 0; $i < count($menuArray); $i++) {
          $tmpParentId = $menuArray[$i]['id'];
          $child = $em->getRepository('AdminPanelMenuBundle:Menu')->getChildByParentId($tmpParentId, $this->container->getParameter('statusActive'));
          if ($child) {
            $childIndex = 0;
            foreach ($child AS $childItem) {
              $menuArray[$i]['child'][$childIndex] = $childItem;
              $childIndex++;
            }
          } else {
            $menuArray[$i]['child'] = null;
          }
        }
        
        return $this->render('AdminPanelContentBundle:Content:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'menuArray' => $menuArray,
        ));
    }

    /**
     * Edits an existing Content entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelContentBundle:Content')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Content entity.');
        }
        
        
        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ContentType(), $entity);
        $editForm->bind($request);
        
        // Check title
        $requestFormArray = $request->request->get('adminpanel_contentbundle_contenttype');        
        $issetTitle = $em->getRepository('AdminPanelContentBundle:Content')->findOtherActiveContentByTitle($requestFormArray['content_title'], $id);
        if($issetTitle)
        {
          $this->get('session')->setFlash('error', 'Уучлаарай өмнө нь хадгалагдсан "'.  $requestFormArray['content_title'].'" гарчигтай идэвхитэй контент байна.');         
          return $this->render('AdminPanelContentBundle:Content:edit.html.twig', array(
                  'entity' => $entity,
                  'edit_form' => $editForm->createView(),
                  'delete_form' => $deleteForm->createView(),
              ));
        }
        
        if ($editForm->isValid()) {  
          
            $em->persist($entity);
            $em->flush();
            
            if(isset($requestFormArray['menu']))
            {
              $menu = $em->getRepository('AdminPanelMenuBundle:Menu')->find($requestFormArray['menu']);
              if($menu){
                $menu->setSlug('/content/'.$entity->getContentTitle());
                $menu->setContentId($entity->getId());
                $em->persist($menu);
                $em->flush();
              }
            }
            
            $this->get('session')->setFlash('notice', $this->container->getParameter('successSave'));
            return $this->redirect($this->generateUrl('content'));
        }
        
        return $this->render('AdminPanelContentBundle:Content:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Content entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AdminPanelContentBundle:Content')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Content entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('content'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}
